package no.sogl.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class PersonPermission {
	@NotNull
    @ManyToOne
    private Person person;

    @NotNull
    @ManyToOne
    private Permission permission;
    
    @NotNull
    private boolean permit;
        
	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	@Column(updatable = false, insertable = true)
	private Date createdAt = new Date();
	
	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "SS")
	private Date updatedAt = new Date();


	public PersonPermission() {
		super();
	}

	public PersonPermission(Person person, Permission permission, boolean permit) {
		super();
		this.person = person;
		this.permission = permission;
		this.permit = permit;
	}

	public static PersonPermission findPersonTagByTag(Tag tag) {
		if (tag == null)
			throw new IllegalArgumentException("The tag argument is required");
		EntityManager em = PersonPermission.entityManager();
		TypedQuery<PersonPermission> q = em.createQuery(
				"SELECT o FROM PersonTag AS o WHERE o.tag = :tag", PersonPermission.class)
				.setMaxResults(1);
		q.setParameter("tag", tag);
		try {
			return q.getSingleResult();
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
	
	@PrePersist
	@PreUpdate
	public void onUpdate() {
		updatedAt = new Date();
	}
}
